from pandas.core.methods.to_dict import to_dict
from app.Mapper.ThingMapper import ThingMapper
from app.Pojo.BThing import BThing
from datetime import datetime


class ThingService:
    def __init__(self, db):
        self.thing_mapper = ThingMapper(db)

    def list_things(self, page, page_size):
        """分页查询商品"""
        things, total = self.thing_mapper.list_things(page, page_size)
        result = {
            'total': total,
            'page': page,
            'pageSize': page_size,
            'list': []
        }

        for thing in things:
            thing_dict = {
                'id': thing.id,
                'title': thing.title,
                'description': thing.description,
                'repertory': thing.repertory,
                'create_time': thing.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                'price': thing.price
            }
            result['list'].append(thing_dict)

        return result

    def delete_things(self, ids):
        """批量删除商品"""
        self.thing_mapper.batch_delete(ids)

    def update_thing(self, data):
        """更新商品信息"""
        thing_id = data.get('id')
        if not thing_id:
            raise ValueError("缺少必要参数: id")

        thing = self.thing_mapper.get_thing(thing_id)
        if not thing:
            raise ValueError("商品不存在")

        # 更新商品信息
        for key, value in data.items():
            if hasattr(thing, key) and key != 'id':
                setattr(thing, key, value)

        thing.update_time = datetime.now()
        self.thing_mapper.save_thing(thing)

        return {
            'id': thing.id,
            'title': thing.title,
            'price': thing.price,
            'status': thing.status,
            'repertory': thing.repertory,
            'update_time': thing.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }

    def get_thing(self, id):
        """根据ID查询商品"""
        thing = self.thing_mapper.get_thing(id)
        if not thing:
            return None

        return {
            'id': thing.id,
            'title': thing.title,
            'cover': thing.cover,
            'description': thing.description,
            'price': thing.price,
            'status': thing.status,
            'repertory': thing.repertory,
            'classification_id': thing.classification_id,
            'create_time': thing.create_time.strftime('%Y-%m-%d %H:%M:%S')
        }

    def create_thing(self, data):
        """新增商品"""
        # 创建商品
        thing = BThing(
            title=data['title'],
            cover=data.get('cover'),
            description=data.get('description'),
            price=data['price'],
            status=data['status'],
            repertory=data['repertory'],
            classification_id=data['classification_id'],
            create_time=datetime.now()
        )

        self.thing_mapper.save_thing(thing)

        return {
            'id': thing.id,
            'title': thing.title,
            'create_time': thing.create_time.strftime('%Y-%m-%d %H:%M:%S')
        }

    def search_things(self, title):
        """根据title模糊查询商品"""
        things = self.thing_mapper.search_things(title)
        return [
            {
                'id': thing.id,
                'title': thing.title,
                'price': thing.price,
                'status': thing.status,
                'repertory': thing.repertory
            }
            for thing in things
        ]
    def delete_thing(self, id):
        """删除商品"""
        thing = self.thing_mapper.get_thing(id)
        if not thing:
            raise ValueError("商品不存在")

        self.thing_mapper.delete_thing(id)